<?php
declare (strict_types=1);

namespace app\index\controller;

use think\facade\Cache;
use think\facade\Log;

class BaseWechat
{
    public $Appid = "wxe4b77d2f0f456b9b";

    public $AppSecret = "98610d87a12e0169eec933fca8f85234";

    /**
     * 获取access_token
     * @return mixed|string
     */
    public function GetToken()
    {
        $token = Cache::get('access_token');

        if (!$token) {
            $token = $this->GetAccessToken();
        }

        Log::write('token:' . json_encode($token), 'error');
        return $token;
    }

    /**
     * token过期，重新获取acsess_token
     * @return string
     */
    protected function GetAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->Appid . "&secret=" . $this->AppSecret;
        $result = httpRequest($url);
        if (!isset($result['access_token'])) {
            Log::write('token获取失败:' . json_encode($result), 'error');
            return "";
        }
        if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
            $result['access_token'] = '';
        }
        Cache::set('access_token', $result['access_token'], 7000);
        return $result['access_token'];
    }

    /**
     * 获取access_token
     * @return mixed|string
     */
    public function GetToken1()
    {
        $token = Cache::get('access_token1');

        if (!$token) {
            $token = $this->GetAccessToken1();
        }

        Log::write('token1:' . json_encode($token), 'error');
        return $token;
    }

    /**
     * token过期，重新获取acsess_token
     * @return string
     */
    protected function GetAccessToken1()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . config('wxapplets.appid') . "&secret=" . config('wxapplets.appsecret');
        $result = httpRequest($url);
        if (!isset($result['access_token'])) {
            Log::write('token1获取失败:' . json_encode($result), 'error');
            return "";
        }
        if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
            $result['access_token'] = '';
        }
        Cache::set('access_token1', $result['access_token'], 7000);
        return $result['access_token'];
    }

    /**
     * 获取ticken
     * @return mixed|string
     */
    public function GetTicken()
    {
        $ticket = Cache::get('ticket');

        if (!$ticket) {
            $ticket = $this->GetWechatTicken();
        }

        Log::write('ticken:' . json_encode($ticket), 'error');
        return $ticket;
    }

    /**
     * ticket过期，重新获取acsess_token
     * @return string
     */
    protected function GetWechatTicken()
    {
        $access_token = $this->GetToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $access_token . "&type=jsapi";
        $result = httpRequest($url);
        if (!isset($result['ticket'])) {
            Log::write('ticket获取失败:' . json_encode($result), 'error');
            return "";
        }
        if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
            $result['ticket'] = '';
        }

        Cache::set('ticket', $result['ticket'], 7000);
        return $result['ticket'];
    }


    /**
     * 响应微信发送的信息 （自动回复）
     * @param string $data
     * @param string $type
     * @param $obj
     */
    protected function PushMessage($data = "", $type = "text", $obj)
    {
        $arr = array(
            "ToUserName" => $obj->FromUserName,
            "FromUserName" => $obj->ToUserName,
            "CreateTime" => $obj->CreateTime,
            "MsgType" => $type,
            'Content' => $data,
        );
        $rews = $this->arraytoxml($arr);
        exit($rews);
    }

    /**
     * [arraytoxml 将数组转换成xml格式（简单方法）:]
     * @param  [type] $data [数组]
     * @return [type]       [array 转 xml]
     */
    protected function arraytoxml($data)
    {
        $str = '<xml>';
        foreach ($data as $k => $v) {
            $str .= '<' . $k . '>' . $v . '</' . $k . '>';
        }
        $str .= '</xml>';
        return $str;
    }

    /**
     * [arraytoxml 将数组转换成xml格式（简单方法）:]
     * @param  [type] $data [数组]
     * @return [type]       [array 转 xml]
     */
    protected function ArrayToXmlImage($data)
    {
        $str = '<xml>';
        foreach ($data as $k => $v) {
            $str .= '<' . $k . '>';
            if (is_array($v)) {
                foreach ($v as $key => $val) {

                    $str .= '<' . $key . '>' . $val . '</' . $key . '>';
                }
            } else {
                $str .= $v;
            }
            $str .= '</' . $k . '>';
        }
        $str .= '</xml>';
        return $str;
    }


    /**
     * [ArrayToXmlNews 将数组转换成xml格式（简单方法）:]  图文专用
     * @param $data
     * @param string $text
     * @return string
     */
    protected function ArrayToXmlNews($data, $text = '')
    {
        $str = '<xml>';
        foreach ($data as $k => $v) {
            $str .= '<' . $k . '>';
            if (is_array($v)) {
                $str .= '<' . $text . '>';
                foreach ($v[$text] as $key => $val) {

                    $str .= '<' . $key . '>' . $val . '</' . $key . '>';
                }
                $str .= '</' . $text . '>';
            } else {
                $str .= $v;
            }
            $str .= '</' . $k . '>';
        }
        $str .= '</xml>';
        return $str;
    }

}
